package com.gzhryc.shared_device.oem.h5.agent.mng;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.jdbc.ConnectionFactory;
import com.gzhryc.jdbc.DateBranchHelper;
import com.gzhryc.jdbc.models.ConnectInfo;
import com.gzhryc.net_marketing.api.CloudGoodsAPIService;
import com.gzhryc.net_marketing.api.CloudGoodsOrderAPIService;
import com.gzhryc.net_marketing.api.CloudPayAccountAPIService;
import com.gzhryc.net_marketing.api.ConfigAPIService;
import com.gzhryc.net_marketing.supplier.Supplier;
import com.gzhryc.net_marketing.supplier.SupplierManager;
import com.gzhryc.net_marketing.supplier.SupplierManager.SupplierInitialListener;
import com.gzhryc.shared_device.common.BusyThreadPool;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.h5.agent.mng.jetty.JettyHttpServer;
import com.gzhryc.servlet.VelocityService;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.*;
import java.util.Properties;

public class Main {

	static Logger log = Logger.getLogger(Main.class);

	public static void main(String[] args) {
		try {
			String path = "config";
			if (args != null && args.length > 0) {
				path = args[0];
			}

			// 获取当前程序路径
			File logCfgFile = new File(path + "/log4j.xml");
			if (logCfgFile.exists()) {
				DOMConfigurator.configure(logCfgFile.getPath());
				log.info("加载" + path + "/log4j.xml日志配置信息");
			} else {
				DOMConfigurator.configure(Main.class.getClassLoader().getResource("log4j.xml"));
				log.info("加载默认log4j.xml日志配置信息");
			}

			File infoCfgFile = new File(path + "/info.properties");
			if (infoCfgFile.exists()) {
				PropertyTools.load(infoCfgFile);
				log.info("加载" + path + "/info.properties配置信息");
			} else {
				PropertyTools.load(Main.class.getClassLoader().getResourceAsStream("info.properties"));
				log.info("加载默认info.properties配置信息");
			}

			File redisCfgFile = new File(path + "/redis.properties");
			if (redisCfgFile.exists()) {
				PropertyTools tools = new PropertyTools(redisCfgFile);
				RedisTools.get().initial(tools.getProperties());
				log.info("加载" + path + "/redis.properties配置信息");
			} else {
				PropertyTools tools = new PropertyTools(Main.class.getClassLoader().getResourceAsStream("redis.properties"));
				RedisTools.get().initial(tools.getProperties());
				log.info("加载默认redis.properties配置信息");
			}

			File jdbcCfgFile = new File(path + "/jdbc.properties");
			if (jdbcCfgFile.exists()) {
				Properties properties = new Properties();
				InputStream inStream = new FileInputStream(jdbcCfgFile);
				BufferedReader bf = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
				properties.load(bf);
				ConnectInfo connectInfoCfg = new ConnectInfo(properties);
				ConnectionFactory.addDataSource(BaseConstants.JDBC_KEY, connectInfoCfg);
				ConnectionFactory.setDefaultJdbcKey(BaseConstants.JDBC_KEY);
				log.info("加载" + path + "/jdbc.properties数据库连接配置信息");
			} else {
				Properties properties = new Properties();
				properties.load(Main.class.getClassLoader().getResourceAsStream("jdbc.properties"));
				ConnectInfo connectInfoCfg = new ConnectInfo(properties);
				ConnectionFactory.addDataSource(BaseConstants.JDBC_KEY, connectInfoCfg);
				ConnectionFactory.setDefaultJdbcKey(BaseConstants.JDBC_KEY);
				log.info("加载默认jdbc.properties数据库连接配置信息");
			}
			
			BusyThreadPool.self().initial();

			PayServiceFactory.self().initial(PropertyTools.get().getString("httpDomain"));
			
			String resDomain = PropertyTools.get().getString("resDomain");
			String resToken = PropertyTools.get().getString("resToken");
			String resId = PropertyTools.get().getString("resId");
			ResourceAPIServer.self().initial(resDomain, resToken, resId);

			//初始化分表查询工具
			DateBranchHelper.self().setDefaultStartDate(BaseConstants.getStartDate());

			//创建临时目录
			String tempPath = PropertyTools.get().getString("tempPath");
			if(StringTools.isNotBlank(tempPath)) {
				File file = new File(tempPath);
				if (!file.exists()) {
					file.mkdirs();
				}
			}
			
			//商城代码
			if(BaseConstants.getMarket()){
				String marketCloudHttpDomain = PropertyTools.get().getString("marketCloudHttpDomain");
				String marketCloudToken = PropertyTools.get().getString("marketCloudToken");
				ConfigAPIService.self().initial(marketCloudHttpDomain);
				CloudPayAccountAPIService.self().initial(marketCloudHttpDomain);
				CloudGoodsAPIService.self().initial(marketCloudHttpDomain);
				CloudGoodsOrderAPIService.self().initial(marketCloudHttpDomain);
				
				SupplierManager.initial(marketCloudToken, new SupplierInitialListener() {
					@Override
					public void execute(Supplier supplier, ConnectInfo info) {
							SupplierManager.createDBAndTable(info);
					}
				});
			}
			
			BusyThreadPool.self().execute(new Runnable() {
				@Override
				public void run() {
					//初始化地区信息
					CountryAreaUtils.initial();
				}
			});

			File kafkaCfgFile = new File(path + "/kafka_producer.properties");
			if (kafkaCfgFile.exists()) {
				PropertyTools propertyTools = new PropertyTools(kafkaCfgFile);
				KafkaProducerFactory.self().initial(propertyTools.getProperties());
				log.info("消息生产者加载" + path + "/kafka_producer.properties配置信息");
			} else {
				log.info("未加载kafka_producer.properties配置信息");
			}

			// 配置模版引擎
			String webapp = PropertyTools.get().getString(WebConstants.PROGRAM_TYPE + ".webapp");
			if (StringUtils.isNotBlank(webapp)) {
				VelocityService.initial(webapp + "/views");
			} else {
				log.error("未能加载页面模版");
				return;
			}
			
			JettyHttpServer.start(path);

		} catch (IOException e) {
			log.error("程序启动失败", e);
		} catch (Exception e) {
			log.error("程序启动失败", e);
		}
	}

}
